import http from '@/api';

export const setForm = (json, configPageParams, mainData): any => {
  // console.log('setForm');

  let formArr = [];

  for (let v of json) {
    const item = {
      ...JSON.parse(v.json).useForm,
      originalOptions: new Map()
    };
    // console.log(item, "item");

    const apis = [];
    // 表单可选项集合
    const enumOptions = new Map();
    // 字典code
    const dictCodes = [];
    // api接口相关配置
    const enumApiData = [];
    // console.log(item.options, 'item.options');

    for (let son of item.options) {
      const { childrenProps, attrs } = son || {};

      // 获取所有的选择项
      if (childrenProps) {
        // console.log(childrenProps, 'childrenPro>>>>>>>>>>>>>>>ps');

        setEnumOptions(enumOptions, dictCodes, enumApiData, apis, childrenProps, son, configPageParams);
      }
      if (attrs?.propsProps) {
        setEnumOptions(enumOptions, dictCodes, enumApiData, apis, attrs?.propsProps, son, configPageParams);
      }

      // 初始化所有表单方法
      setFormMethods(son, configPageParams);
    }

    item.initForm = {
      openInitForm: async () => openInitForm(dictCodes, enumOptions, apis, enumApiData, item)
    };

    const { submitForm } = item.saveForm || {};

    item.saveForm = {
      submitForm: async form => {
        // 提交表单
        if (submitForm && typeof submitForm === 'string') {
          const submitFormFun = new Function('form', 'configPageParams', `return (async () => { ${submitForm} })()`);
          await submitFormFun(form, configPageParams);
          // 关闭对应表单弹框
          configPageParams.formRefs[item.ref].updateDialogFormStatus(false);
        }

        item.visible = false;
        elMessage();
      }
    };

    configPageParams.formObj[item.ref] = item;
    setModes(configPageParams, item);

    formArr.push(item);
  }

  mainData.mainForms.formArr = formArr;
};

/**设置使用的模块 */
const setModes = async (configPageParams, item) => {
  for (let v of item.usePlugIn) {
    switch (v) {
      case 'pinyin':
        if (!configPageParams.dynamicModes.pinyin) {
          configPageParams.dynamicModes.pinyin = await import('js-pinyin');

          // configPageParams.dynamicModes.pinyin.default.setOptions({ checkPolyphone: false, charCase: 0 });
          // const name = configPageParams.dynamicModes.pinyin.default.getCamelChars('测试');
        }
        break;
      case 'formUtils':
        if (!configPageParams.dynamicModes.formUtils) {
          // console.log('???????????????????');

          configPageParams.dynamicModes.formUtils = await import('@/utils/form');
        }
        break;
    }
  }
};

/**设置下拉列表options */
const setEnumOptions = (enumOptions, dictCodes, enumApiData, apis, childrenProps, son, configPageParams) => {
  const { type, options } = childrenProps || {};
  // console.log(type, '???????????');

  if (type === 'options') {
    if (options) {
      enumOptions.set(son.prop, JSON.parse(options));
    }
  } else if (type === 'dict') {
    dictCodes.push(son);
  } else if (type === 'api') {
    enumApiData.push(son);

    const { api } = childrenProps || {};
    if (api && typeof api === 'string') {
      const method = new Function('configPageParams', `return (async () => { ${api} })()`);
      apis.push(() => method(configPageParams));
    }
  }
};

/**初始化表单获取下拉选择项 */
const openInitForm = async (dictCodes, enumOptions, apis, enumApiData, item) => {
  // 对api请求进行统一的处理
  if (apis.length) {
    const resArr = await Promise.all(apis.map(v => v()));

    for (let i = 0; i < enumApiData.length; i++) {
      const _item = enumApiData[i];
      const { prop } = _item || {};
      item.originalOptions.set(prop, resArr[i]);
      // api请求的自己装换不提供装换逻辑
      enumOptions.set(prop, resArr[i]);
    }
  }

  if (dictCodes.length) {
    const code = dictCodes.map(v => v.childrenProps.dictCode);
    // 统一获取数据字典值
    const dictObj: any = await getDictionaryListByCodes(code);

    for (let d of dictCodes) {
      const { prop } = d || {};
      const { label, value, dictCode } = d.childrenProps || {};

      item.originalOptions.set(prop, dictObj[dictCode]);
      enumOptions.set(prop, arrTransitionSelectData(dictObj[dictCode], label, value));
    }
  }

  for (let v of item.options) {
    if (enumOptions.has(v.prop)) {
      if (v.type === 'tree-select') {
        v.attrs.data = enumOptions.get(v.prop);
      } else {
        v.children = enumOptions.get(v.prop);
      }
    }
  }
};

/**
 * 设置表单的方法
 */
export const setFormMethods = (son, configPageParams) => {
  if (!son) return;

  const methods = ['inputMethod', 'calendarChange', 'blurFunction', 'changeMethod'];
  for (let m of methods) {
    if (typeof son[m] === 'string') {
      const method = new Function('form', 'configPageParams', son[m]);
      son[m] = form => method(form, configPageParams);
    }
  }
};
